﻿using Common.EdgeBytes;
using MQXT.BLL;
using MQXT.Repository.DAL;
using MQXT.Repository.Model;
using Oliving.CommonPC.Log;
using ScokTcpLibB;
using ScokTcpLibB.ScokTcpServer;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketTool.Socket
{
    public static class TcpipJzq
    {


        #region 参数


        private static FzidPraser _praser;
        public static int _port = 6000;


        #endregion


        #region MyRegion



        public static void InitSocket()
        {
            try
            {
                _port = Convert.ToInt32(ConfigurationManager.AppSettings["TCPIP_JZQ"]);
            }
            catch (Exception ex)
            {
                //记录服务器错误信息 
                EdgeLog.writeLog("JZQ_Service", (ex).ToString());
                return;
            }
            _praser = new FzidPraser();

            //创建服务器
            SocketComm.InitSocketServer(_port);

            SocketComm.getSockSvr().ClientConn += OnClientConn;
            SocketComm.getSockSvr().ClientClose += OnClientClose;

            SocketComm.getSockSvr().RecvData += OnRecvData;
        }


        #region 处理事件

        /// <summary>
        ///  客户端连接事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnClientConn(object sender, NetEventArgs e)
        {
            try
            {
                EdgeLog.writeLog("JZQ_wpServoce", "Tcpip链接");

                //BeginInvoke(new ShowClientCountDele(ShowClientCount), new object[] { SocketComm.getSockSvr().SessionCount });
            }
            catch (System.Exception ex)
            {

            }
        }



        /// <summary>
        ///  客户端关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnClientClose(object sender, NetEventArgs e)
        {

            try
            {
                EdgeLog.writeLog("JZQ_wpServoce", "Tcpip断开链接");
                //BeginInvoke(new ShowClientCountDele(ShowClientCount), new object[] { SocketComm.getSockSvr().SessionCount });
            }
            catch (System.Exception ex)
            {

            }
        }

        /// <summary>
        ///  接受数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnRecvData(object sender, NetEventArgs e)
        {

            string stringdata = BitConverter.ToString(e.Client.Datagram, 0, e.Client.DatagramLen);
            string strMsg = Encoding.UTF8.GetString(e.Client.Datagram, 0, e.Client.DatagramLen);

            //EdgeLog.writeLog("jzq_OnRecvData", stringdata); // 16进制数据
            //EdgeLog.writeLog("jzq_OnRecvDataA", strMsg);    // 字符串
            //EdgeLog.writeLog("jzq_Count", SocketComm.getSockSvr().SessionCount + "");    // 字符串

            string result = "";
            int addr = 0;
            byte[] byteData = e.Client.Datagram.Take(e.Client.DatagramLen).ToArray();
            int isSend = TcpipJzq.Check_ZhuCe(strMsg, byteData, out result, e.Client.ID.ID, out addr);

            #region 恢复集中器数据 isSend == 2 

            if (isSend == 2 && !string.IsNullOrEmpty(result))
            {
                // 发送 result 
                byte[] bytTemp2 = BytesHelper.EdgeGetBytes(result);
                string sendData = BitConverter.ToString(bytTemp2, 0, bytTemp2.Length);
               

                Thread.Sleep(500);

                bool a = SocketComm.getSockSvr().Send(e.Client, bytTemp2, bytTemp2.Length, 0);
                // bool b = SocketComm.getSockSvr().Send(e.Client, "dvdvdv");
                
            }

            #endregion

            else if (isSend == 3)
            {
                Thread.Sleep(500);
                byte[] bytTemp2 = BytesHelper.EdgeGetBytes(result);
                bool a = SocketComm.getSockSvr().Send(e.Client, bytTemp2, bytTemp2.Length, 0);
                 
                Thread thread = new Thread(() =>
                {
                    TcpipCjq.EdgeSend(addr, result);
                });
                thread.IsBackground = true;
                thread.Start();





            }

        }









        #endregion

        #endregion



        /// <summary>
        /// 验证是否有注册信息
        /// </summary>
        /// <param name="dataContent"></param>
        /// <returns></returns>
        public static int Check_ZhuCe(string dataContent, byte[] byteData, out string result, int sessionID, out int addr)
        {
            int resultInt = 0;
            addr = 0;
            result = "";
            //       byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(content);
            // dataContent =  addr:12345678;sim:14541358567;yb:001;gps:111.111111111.111111;ver:JZQ;over;
            bool isBegin = (dataContent.Substring(0, 5) == "addr:");
            int isEnd = dataContent.IndexOf(";over;");


            if (isBegin && (isEnd > 0))
            {

                #region 注册

                dataContent = dataContent.Substring(0, isEnd);
                if (dataContent.Contains("sim:")
                 && dataContent.Contains("yb:")
                 && dataContent.Contains("gps:")
                 && dataContent.Contains("ver:")
                 )
                {
                    JiZhongQiModel jzq = EdgeConvert(dataContent);

                    JiZhongQiModelService bll = new JiZhongQiModelService();
                    jzq.SesssionID = sessionID.ToString();
                    bll.AddOrUpdate(jzq);
                     
                }
                #endregion
                resultInt = 1;
                return resultInt;
            }
            else
            {

                byte[] byteArray = byteData;// System.Text.Encoding.UTF8.GetBytes(dataContent);

                if (byteArray.Length == 12
                    && byteArray[0] == 0x00
                    && byteArray[1] == 0x00
                    && byteArray[2] == 0x00
                    && byteArray[3] == 0x00
                    && byteArray[4] == 0x00
                    && byteArray[5] == 0x06

                    && byteArray[7] == 0x03

                    )
                {

                    #region 功能码03


                    // 地址 01 
                    addr = Convert.ToInt32(byteArray[6].ToString());

                    // 寄存器地址 
                    int jcq_addr = toInt(byteArray[8], byteArray[9]);

                    // 寄存器长度 
                    int jcq_Length = toInt(byteArray[10], byteArray[11]);



                    result = "00-00-00-00-00";


                    result = result + "-" + ((jcq_Length * 2) + 3).ToString("X").PadLeft(2, '0'); // 数据长度
                    result = result + "-" + (Convert.ToInt32(byteArray[6].ToString())).ToString("X").PadLeft(2, '0');                             // 地址码
                    result = result + "-" + (3).ToString("X").PadLeft(2, '0');                                    // 功能码
                    result = result + "-" + ((jcq_Length * 2)).ToString("X").PadLeft(2, '0');                     // 数据长度



                    for (int i = 0; i < jcq_Length; i++)
                    {
                        DataShowModelService dal = new DataShowModelService();
                        string aVal = dal.GetData(addr.ToString(), jcq_addr + i);

                        if (string.IsNullOrEmpty(aVal))
                        {
                            result = "00-00-00-00-00-04-03-03-01-81";
                            return 2;
                        }
                        byte[] byteArrayAA = toInt(Convert.ToInt32(aVal));

                        result = result + "-" + (byteArrayAA[0]).ToString("X").PadLeft(2, '0');
                        result = result + "-" + (byteArrayAA[1]).ToString("X").PadLeft(2, '0');

                    }
                    try
                    {
                        #region 更新集中器在线时间

                        JiZhongQiModelService bll = new JiZhongQiModelService();


                        JiZhongQiModel dtoDB = bll.Query("   SesssionID='" + sessionID + "'").FirstOrDefault();

                        if (dtoDB == null || dtoDB.Id == 0)
                        {
                        }
                        else
                        {
                            dtoDB.UpdateTIme = DateTime.Now;
                            bll.EdgeUpdate(dtoDB);
                        }

                        #endregion
                    }
                    catch (Exception ee)
                    {
                        EdgeLog.writeLog("jzq_Check_ZhuCe_Exception", ee.ToString());    // 字符串
                    }


                    #endregion
                    resultInt = 2;
                    return resultInt;
                }
                else if (byteArray.Length == 12
                    && byteArray[0] == 0x00
                    && byteArray[1] == 0x00
                    && byteArray[2] == 0x00
                    && byteArray[3] == 0x00
                    && byteArray[4] == 0x00
                    && byteArray[5] == 0x06

                    && byteArray[7] == 0x06

                    )
                {
                    #region 功能码06

                    result = BitConverter.ToString(byteArray, 0, byteArray.Length);

                    // 地址 01 // 向所有的地址发送消息 
                    addr = Convert.ToInt32(byteArray[6].ToString());

                    resultInt = 3;

                    EdgeLog.writeLog("功能码06", resultInt + "=>" + addr);
                    return resultInt;

                    #endregion
                }

            }


            return resultInt;
        }



        public static JiZhongQiModel EdgeConvert(string dataContent)
        {

            JiZhongQiModel dto = new JiZhongQiModel();

            string[] dMsg = dataContent.Split(';');

            dto.Addr = dMsg[0].Replace("addr:", "");
            dto.SIM = dMsg[1].Replace("sim:", "");
            dto.Yb = dMsg[2].Replace("yb:", "");
            dto.GPS = dMsg[3].Replace("gps:", "");

            dto.Ver = dMsg[4].Replace("ver:", "");

            dto.UpdateTIme = DateTime.Now;



            return dto;
        }

        public static int toInt(byte high, byte low)
        {

            int val = (high & 0xFF) << 8 | low;
            return val;
        }

        public static byte[] toInt(int value)
        {
            byte lowByte = (byte)(value & 0xff);
            byte highByte = (byte)((value >> 8) & 0xff);

            return new byte[] { highByte, lowByte };
        }


        //        00 00 00 00 00  TCP数据头
        //04:长度
        //03:  地址
        //03:功能码
        //01: 长度
        //81:  数据 
        static byte[] dataError = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x03, 0x03, 0x01, 0x81 };
        //                                 

    }
}
